package it.mypofolio.http;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 * @author  Paolo Cappelletti (Gempliss Srl)
 */
public class HttpCrawler {
	
	public CrawlerResult load(String sigla) throws ClientProtocolException, IOException{
        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpGet httpget = new HttpGet("http://it.finance.yahoo.com/q?s="+sigla);

            // Create a response handler
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httpget, responseHandler);
            
            double quotationDBL=0;
            String ora=null;
            
            //quotatzione
            String startSTR="Ultimo scambio:</th><td class=\"yfnc_tabledata1\"><big><b><span ";
            int find=responseBody.indexOf(startSTR);
            if (find!=-1){
            	String newStr=responseBody.substring(find+startSTR.length());
            	int startInd=newStr.indexOf(">");
            	if (startInd!=-1){
            		newStr=newStr.substring(startInd+1);
            		int endInd=newStr.indexOf("</span>");
            		
            		String quotation=newStr.substring(0,endInd);
            		quotation=quotation.replace(",",".");
            		quotationDBL=Double.parseDouble(quotation);
            	}
            }
            
            
            //ora
            startSTR="Orario scambio:</th><td class=\"yfnc_tabledata1\"><span ";
            find=responseBody.indexOf(startSTR);
            if (find!=-1){
            	String newStr=responseBody.substring(find+startSTR.length());
            	int startInd=newStr.indexOf(">");
            	if (startInd!=-1){
            		newStr=newStr.substring(startInd+1);
            		int endInd=newStr.indexOf("</span>");
            		
            		ora=newStr.substring(0,endInd);
            	}
            }
            
            if (ora!=null && quotationDBL!=0){
            	return new CrawlerResult(quotationDBL, ora);
            }
            

        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
        
        return null;
	}
	
	public static void main(String[] args) throws ClientProtocolException, IOException {
		HttpCrawler test=new HttpCrawler();
		CrawlerResult res=test.load("ENI.MI");
    	System.out.println(res.getOra());
	}

}
